package com.scheduling.user.controller;

import com.scheduling.common.result.Result;
import com.scheduling.common.result.ResultCode;
import com.scheduling.user.dto.UserLoginRequest;
import com.scheduling.user.dto.UserLoginResponse;
import com.scheduling.user.dto.UserRegisterRequest;
import com.scheduling.user.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户控制类
 *
 * @author 李贝依
 * @since 1.0.0
 */
@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*")
@Tag(name = "用户管理", description = "用户信息管理及登陆注册")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户注册
     */
    @Operation(summary = "用户注册", description = "新用户注册接口")
    @PostMapping("/user/register")
    public ResponseEntity<Result<Void>> register(@Valid @RequestBody UserRegisterRequest request) {
        log.info("用户注册请求: {}", request.getUsername());

        Result<Void> result = userService.register(request);

        // 根据ResultCode判断HTTP状态码
        if (result.getCode() == Result.SUCCESS_CODE) {
            log.info("用户注册成功: {}", request.getUsername());
            return ResponseEntity.ok(result);
        } else if (isParamError(result.getCode())) {
            // 参数错误返回400
            log.warn("用户注册参数错误: {}, 错误信息: {}", request.getUsername(), result.getMessage());
            return ResponseEntity.badRequest().body(result);
        } else if (result.getCode() == ResultCode.DATA_ALREADY_EXISTS.getCode()) {
            // 用户已存在返回409冲突
            log.warn("用户注册失败，用户已存在: {}", request.getUsername());
            return ResponseEntity.status(HttpStatus.CONFLICT).body(result);
        } else {
            // 其他业务错误返回200，通过result.code区分
            log.error("用户注册失败: {}, 错误信息: {}", request.getUsername(), result.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 用户登录
     */
    @Operation(summary = "用户登录", description = "用户登录接口")
    @PostMapping("/user/login")
    public ResponseEntity<Result<UserLoginResponse>> login(@Valid @RequestBody UserLoginRequest request) {
        log.info("用户登录请求: {}", request.getUsername());

        Result<UserLoginResponse> result = userService.login(request);

        // 根据ResultCode判断HTTP状态码
        if (result.getCode() == Result.SUCCESS_CODE) {
            log.info("用户登录成功: {}", request.getUsername());
            return ResponseEntity.ok(result);
        } else if (isAuthError(result.getCode())) {
            // 认证相关错误返回401
            log.warn("用户登录认证失败: {}, 错误信息: {}", request.getUsername(), result.getMessage());
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(result);
        } else if (isParamError(result.getCode())) {
            // 参数错误返回400
            log.warn("用户登录参数错误: {}, 错误信息: {}", request.getUsername(), result.getMessage());
            return ResponseEntity.badRequest().body(result);
        } else {
            // 其他业务错误返回200，通过result.code区分
            log.error("用户登录失败: {}, 错误信息: {}", request.getUsername(), result.getMessage());
            return ResponseEntity.ok(result);
        }
    }


    /**
     * 用户退出登录
     */
    @Operation(summary = "用户退出登录", description = "用户退出登录接口")
    @PostMapping("/main/logout")
    public ResponseEntity<Result<String>> logout(HttpServletRequest request) {
        log.info("用户退出登录请求");

        Result<Void> serviceResult = userService.logout(request);

        if (serviceResult.getCode() == Result.SUCCESS_CODE) {
            // 成功时返回跳转地址
            log.info("用户退出登录成功");
            Result<String> result = Result.success("/user/login", "退出登录成功");
            return ResponseEntity.ok(result);
        } else {
            log.error("用户退出登录失败，错误信息: {}", serviceResult.getMessage());
            Result<String> result = Result.error(serviceResult.getCode(), serviceResult.getMessage());

            // 根据错误类型返回不同的HTTP状态码
            if (serviceResult.getCode() == ResultCode.UNAUTHORIZED.getCode()) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(result);
            }
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 用户注销账号
     */
    @Operation(summary = "用户注销账号", description = "用户注销账号接口")
    @DeleteMapping("/main/account")
    public ResponseEntity<Result<String>> deleteAccount(Authentication authentication) {
        log.info("用户注销账号请求");

        if (authentication == null || authentication.getPrincipal() == null) {
            log.warn("账号注销失败：用户未认证");
            Result<String> result = Result.error(ResultCode.UNAUTHORIZED.getCode(),
                    ResultCode.UNAUTHORIZED.getMessage());
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(result);
        }

        String userId = authentication.getName();
        log.info("用户注销账号: {}", userId);

        Result<Void> serviceResult = userService.deleteAccount(userId);

        if (serviceResult.getCode() == Result.SUCCESS_CODE) {
            // 成功时返回跳转地址
            log.info("用户账号注销成功: {}", userId);
            Result<String> result = Result.success("/user/login", "账号注销成功");
            return ResponseEntity.ok(result);
        } else if (serviceResult.getCode() == ResultCode.USER_NOT_FOUND.getCode()) {
            // 用户不存在返回404
            log.warn("账号注销失败，用户不存在: {}", userId);
            Result<String> result = Result.error(serviceResult.getCode(), serviceResult.getMessage());
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
        } else if (serviceResult.getCode() == ResultCode.OPERATION_NOT_ALLOWED.getCode()) {
            // 操作不被允许返回403
            log.warn("账号注销失败，操作不被允许: {}", userId);
            Result<String> result = Result.error(serviceResult.getCode(), serviceResult.getMessage());
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body(result);
        } else {
            log.error("用户账号注销失败: {}, 错误信息: {}", userId, serviceResult.getMessage());
            Result<String> result = Result.error(serviceResult.getCode(), serviceResult.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 判断是否为参数错误
     *
     * @param code 错误码
     * @return 是否为参数错误
     */
    private boolean isParamError(Integer code) {
        return code >= 400 && code <= 499;
    }

    /**
     * 判断是否为认证授权错误
     *
     * @param code 错误码
     * @return 是否为认证授权错误
     */
    private boolean isAuthError(Integer code) {
        return code >= 1000 && code <= 1099;
    }
}